package com.welike.shibo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.welike.shibo.utils.Constants.ACCOUNT;

/**
 * Controller 控制器基类
 * Session管理
 * @author fangyu
 * @version v1.0.0
 * @since 2019-08-20 17:46
 */

@Slf4j
public abstract class BaseController {


    protected Map<String, Object> map = new HashMap<String, Object>(1);

    private HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public Object getUser4Session(){
        HttpSession session = getRequest().getSession();
        return session.getAttribute(ACCOUNT);
    }

    public void setSession(Object object){
        HttpSession session = getRequest().getSession();
        if (object!=null) {
            session.setAttribute(ACCOUNT, object);
            // session过期时间设置, 以秒为单位, 即在没有活动10天后, session失效
            session.setMaxInactiveInterval(10 * 24 * 60 * 60);
        }
        log.info("setSession: user ==> {}", object);
    }

    public void emptySession(Object object){
        HttpSession session = getRequest().getSession();
        session.setAttribute(ACCOUNT, object);
    }

    public void addModel(Model model, IPage iPage, String name){
        model.addAttribute("page", iPage.getCurrent());
        model.addAttribute("pageSize", iPage.getSize());
        model.addAttribute("total", iPage.getTotal());
        model.addAttribute("pages", iPage.getPages());
        // 是否首页
        boolean isFirst = false;
        // 是否尾页
        boolean isLast = false;
        if (iPage.getCurrent() == 1){
            isFirst = true;
        }
        if (iPage.getCurrent() == iPage.getPages()){
            isLast = true;
        }
        model.addAttribute("isFirst", isFirst);
        model.addAttribute("isLast", isLast);
        model.addAttribute("pre", iPage.getCurrent() - 1);
        model.addAttribute("next", iPage.getCurrent() + 1);
        model.addAttribute(name, iPage.getRecords());
    }
}